//
//  MyCollectionViewLayout.m
//  15-HomeWork(CustomCollectionViewCell)
//
//  Created by ParkourH on 16/8/3.
//  Copyright © 2016年 ParkourH. All rights reserved.
//

#import "MyCollectionViewLayout.h"

@interface MyCollectionViewLayout ()

// item的高度
@property (nonatomic, assign) CGFloat itemHeight;
// 属性item的数组
@property (nonatomic, strong) NSMutableArray<UICollectionViewLayoutAttributes *> *mArrOfAttributes;

// 内容宽度
@property (nonatomic, assign) CGFloat contentWidth;
// item 间距
@property (nonatomic, assign) CGFloat cellMargin;
@end

@implementation MyCollectionViewLayout
#if 1
- (instancetype)init {

    self = [super init];
    if (self) {
        
        _mArrOfAttributes = [NSMutableArray array];
        

        _contentWidth = 0.0f;
        _cellMargin = 5.0f;
        
    }
    return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        
        _mArrOfAttributes = [NSMutableArray array];
        
        
        _contentWidth = 0.0f;
        _cellMargin = 5.0f;
        
    }
    return self;

}

- (CGFloat)itemHeight {

    return CGRectGetHeight(self.collectionView.bounds) * 2 / 3;
}

/** 计算每个item大小 */
- (void)prepareLayout {
    
    self.contentWidth = 0.0f;
    // 清空LayoutAttributes数组
    if (_mArrOfAttributes.count != 0) {
    
        [_mArrOfAttributes removeAllObjects];
    }
    NSLog(@"+++++++++++++++++%ld",  [self.collectionView numberOfItemsInSection:0]);
    // 存储宽度
    CGFloat lineWidth = 0.0f;
    // 遍历collectionView 0 区的所有item
    for (int i = 0; i < [self.collectionView numberOfItemsInSection:0]; i++) {
        
        NSIndexPath *index = [NSIndexPath indexPathForItem:i inSection:0];
        // 创建系统需要的布局描述类
        UICollectionViewLayoutAttributes *layoutAttributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:index];
        // 起始位置
    
        CGFloat x = lineWidth + _cellMargin;
        // 宽度数组中, 最小行对应的宽度
        CGFloat y = _cellMargin * 2;
        // 通过代理方法计算得出文本宽度
        CGFloat width = 0.0f;
        if ([self.delegate respondsToSelector:@selector(collectionView:layout:heightForItemAtIndexPath:)]) {
    
            width = [self.delegate collectionView:self.collectionView layout:self heightForItemAtIndexPath:index];
        }
        // 根据行数, 计算出高度
        CGFloat height = self.itemHeight;
    
        layoutAttributes.frame = CGRectMake(x, y, width, height);
        [_mArrOfAttributes addObject:layoutAttributes];
    
        // 更新数组中对应的宽度
       lineWidth = lineWidth + width +_cellMargin;
    
            // 整个内容的最大宽度
       self.contentWidth = lineWidth;
        
    }
    
}

/** 返回的是, 每个item对应的布局属性 */
- (nullable NSArray<__kindof UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {

    return _mArrOfAttributes;
}
/** 负责CollectionView的滚动范围 */
- (CGSize)collectionViewContentSize {

    return CGSizeMake(_contentWidth, 0);
}

#endif
@end
